
package conf2;

import conf2.model.EActor;
import conf2.model.ETerritory;
import conf2.model.Move;
import conf2.ui.GamePiece;
import conf2.ui.PieceCollection;
import conf2.ui.RegionBounds;
import java.awt.Point;
import java.util.LinkedList;
import java.util.List;
import javax.swing.SwingWorker;

public class Animation extends SwingWorker<Void, Void> {

    public static interface Listener {
        void animationFinished();
    }

    private final Move move;
    private final List<Listener> listeners = new LinkedList<Listener>();
    private final PieceCollection pieceColl;
    private final EActor who;
    private final ETerritory to;
    private final GamePiece piece;
    private final Point p1,  p0;
    private final double xstep,  ystep;

    public Animation(
            final PieceCollection pc,
            final Move move) {
        this.pieceColl = pc;
        this.move = move;

        who = move.getAttacker();
        to = move.getTo();

        piece = pieceColl.get(who);

        if (move.getDefender() == null) {
            p1 = RegionBounds.getCenterPoint(to);
            p1.x -= piece.getWidth() / 2;
            p1.y -= piece.getHeight() / 2;
        } else {
            p1 = pieceColl.get(move.getDefender()).getLocation();
        }

        p0 = piece.getLocation();

        xstep = (p1.x - p0.x) / (double) Animator.NSTEPS;
        ystep = (p1.y - p0.y) / (double) Animator.NSTEPS;
    }

    @Override
    protected Void doInBackground() throws Exception {

        double x = p0.x, y = p0.y;
        for (int step = 0; step < Animator.NSTEPS; x += xstep, y += ystep, step++) {
            piece.setLocation((int) x, (int) y);

            try {
                Thread.sleep(Animator.DELAY);
            } catch (InterruptedException e) {
            }
        }

        for (Listener l : listeners) {
            l.animationFinished();
        }

        return null;
    }

    public void addAnimationListener(Listener l) {
        listeners.add(l);
    }
}